package com.liu.yubi.bimq;

import cn.hutool.json.JSONUtil;
import com.liu.yubi.model.entity.Chart;
import com.liu.yubi.model.enums.ChartStatusEnum;
import com.liu.yubi.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author lqh
 * @since 2025-07-10 17:23
 * 死信消费者
 */
@Component
@Slf4j
public class TtlQueueConsumer {

    @Resource
    private ChartService chartService;


    @SneakyThrows
    @RabbitListener(queues = {"YuBi_dead_queue"}, ackMode = "MANUAL") //指定消费者监听那个队列和消息确认机制
    public void doTTLMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        if (StringUtils.isEmpty (message)){
            log.error ("死信队列收到的消息为空");
            //拒绝消费
            channel.basicAck (deliveryTag, false);
        }
        MQMessage ms = JSONUtil.toBean (message, MQMessage.class);
        Long chartId  = ms.getChartId ();
        log.info ("已经接收到死信队列的消息:{}", chartId);
        Chart chart = chartService.getById (chartId);
        if (chart!=null){
            chart.setStatus (ChartStatusEnum.FAILED.getValue ());
            chart.setGenChart ("无生成图表");
            chart.setGenResult ("无生成结果");
            chart.setExecMessage ("消息队列执行失败");
            chartService.updateById (chart);
        }
        channel.basicAck (deliveryTag,false);
    }

    }
